package cn.yangtianxia.org.service.impl;

import cn.yangtianxia.basic.service.Impl.BaseServiceImpl;
import cn.yangtianxia.org.domain.Department;
import cn.yangtianxia.org.mapper.DepartmentMapper;
import cn.yangtianxia.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 部门service实现类
 */
@Service//service注解
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent() == null){
                department.setDirPath("/" + department.getId());
        }
        else {
            Department parent = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(parent.getDirPath() + "/" + department.getId());
        }
        departmentMapper.update(department);
    }

    /**
     * 无限极部门树
     * @return
     */
    @Override
    public List<Department> queryTree() {
        List<Department> departments = departmentMapper.loadAll();
        /*Stream<Department> allMap = departments.stream(Collectors.toMap(Department::getId, temp -> temp));*/
        HashMap<Long, Department> allMap = new HashMap<>();
        for (Department department : departments){
            allMap.put(department.getId(),department);
        }
        List<Department> depts = new ArrayList<>();
        for(Department temp : departments){
            if(temp.getParent_id() == null){
                depts.add(temp);
            } else {
                Department parent = allMap.get(temp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return depts;
    }
}
